package com.heima.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.PageResponse;
import com.heima.entity.*;
import com.heima.mapper.TbBusinessMapper;

import com.heima.mapper.TbRegionMapper;
import com.heima.pojo.vo.NodeCountVo;
import com.heima.pojo.vo.TbNodeVo;
import com.heima.pojo.vo.TbRegionVo;
import com.heima.pojo.vo.TbVendingMachineVo;
import com.heima.service.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 点位表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-06-08
 */
@RestController
@RequestMapping("/api/vm-service")
public class TbNodeController {

    @Autowired
    private ITbNodeService iTbNodeService;

    @Autowired
    private TbRegionMapper tbRegionMapper;

    @Autowired
    private ITbBusinessService iTbBusinessService;

    @Autowired
    private TbBusinessMapper tbBusinessMapper;

    @Autowired
    private ITbVendingMachineService iTbVendingMachineService;

    @Autowired
    private ITbVmTypeService iTbVmTypeService;

    @Autowired
    private ITbPartnerService iTbPartnerService;


    @GetMapping("/node/search")
    public PageResponse<TbNodeVo> selectNode(@RequestParam(value = "pageIndex",required = false) Integer pageIndex,
                                             @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                             @RequestParam(value = "name",required = false) String name,
                                             @RequestParam(value = "regionId",required = false) String regionId){
        //设置分页
        Page<TbNode> page = new Page<>(pageIndex,pageSize);

        //构造条件
        LambdaQueryWrapper<TbNode> wrapper = new QueryWrapper<TbNode>().lambda()
                .like(name != null, TbNode::getName, name)
                .like(regionId != null, TbNode::getRegionId,regionId);
        iTbNodeService.page(page,wrapper);
        List<TbNodeVo> tbNodeVoList = page.getRecords().stream().map(r -> {
            Long regionId1 = r.getRegionId();
            Integer count = iTbNodeService.lambdaQuery()
                    .eq(regionId1 != null,TbNode::getRegionId,regionId1)
                    .count();
            String id = r.getId();
            Integer vmCount = iTbVendingMachineService.lambdaQuery()
                    .eq(id != null, TbVendingMachine::getNodeId, id)
                    .count();
            //获取区域
            TbRegion tbRegion = tbRegionMapper.selectById(regionId1);
            TbRegionVo tbRegionVo = new TbRegionVo();
            BeanUtil.copyProperties(tbRegion, tbRegionVo);
            tbRegionVo.setNodeCount(count);

            //获取类型
            TbNodeVo tbNodeVo = new TbNodeVo();
            tbNodeVo.setVmCount(vmCount);
            TbBusiness business = iTbBusinessService.getById(r.getBusinessId());
            BeanUtil.copyProperties(r, tbNodeVo);
            BusinessType businessType = BeanUtil.toBean(business, BusinessType.class);
            tbNodeVo.setBusinessType(businessType);
            tbNodeVo.setRegion(tbRegionVo);
            return tbNodeVo;
        }).collect(Collectors.toList());
        //封装并返回结果
        PageResponse<TbNodeVo> response = new PageResponse<>();
        response.setPageIndex(pageIndex);
        response.setPageSize(pageSize);
        response.setTotalCount((int) page.getTotal());
        response.setCurrentPageRecords(tbNodeVoList);

        return response;
    }
    @GetMapping("/businessType")
    public List<TbBusiness> selectBusiness(){
        List<TbBusiness> tbBusinesses = tbBusinessMapper.selectList(null);
        return tbBusinesses;
    }
    @PostMapping("/node")
    public Boolean addNode(@RequestBody TbNode tbNode){
        TbNode tbNode1 = new TbNode();
        tbNode1.setName(tbNode.getName());
        tbNode1.setAddr(tbNode.getAddr());
        tbNode1.setAreaCode(tbNode.getAreaCode());
        tbNode1.setBusinessId(tbNode.getBusinessId());
        tbNode1.setCreateUserId(tbNode.getCreateUserId());
        tbNode1.setRegionId(tbNode.getRegionId());
        tbNode1.setOwnerId(tbNode.getOwnerId());
        tbNode1.setOwnerName(tbNode.getOwnerName());
        tbNode1.setUpdateTime(LocalDateTime.now());
        tbNode1.setCreateTime(LocalDateTime.now());
        boolean flag = iTbNodeService.save(tbNode1);
        return flag;
    }
    @GetMapping("/node/vmList/{nodeId}")
    public List<TbVendingMachineVo> getNodeInfo(@PathVariable("nodeId") String nodeId){
        QueryWrapper<TbVendingMachine> wrapper = new QueryWrapper<>();
        wrapper.eq("node_id",nodeId);
        List<TbVendingMachine> machines = iTbVendingMachineService.lambdaQuery()
                .eq(nodeId != null, TbVendingMachine::getNodeId, nodeId)
                .list();
        List<TbVendingMachineVo> machineVoList = machines.stream().map(m -> {
            TbVendingMachineVo vo = new TbVendingMachineVo();

            //查询机器类型
            Integer vmType = m.getVmType();
            TbVmType type = iTbVmTypeService.lambdaQuery()
                    .eq(vmType != null, TbVmType::getTypeId, vmType)
                    .one();
            //查询点位
            TbNodeVo node = new TbNodeVo();
            TbNode tbNode = iTbNodeService.getById(nodeId);
            //查询点位机器数量
            Integer vmCount = iTbVendingMachineService.lambdaQuery()
                    .eq(nodeId != null, TbVendingMachine::getNodeId, nodeId)
                    .count();


            //查询地区
            TbRegionVo tbRegionVo = new TbRegionVo();
            QueryWrapper<TbRegion> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("id", tbNode.getRegionId());
            TbRegion tbRegion = tbRegionMapper.selectOne(wrapper1);
            Long id = tbRegion.getId();
            Integer nodeCount = iTbNodeService.lambdaQuery()
                    .eq(id != null, TbNode::getRegionId, id)
                    .count();
            BeanUtil.copyProperties(tbRegion, tbRegionVo);
            tbRegionVo.setNodeCount(nodeCount);

            //查询商圈类型
            Integer businessId = tbNode.getBusinessId();
            TbBusiness business = iTbBusinessService.lambdaQuery()
                    .eq(businessId != null, TbBusiness::getId, businessId)
                    .one();
            BusinessType businessType = BeanUtil.toBean(business, BusinessType.class);
            node.setBusinessType(businessType);
            node.setRegion(tbRegionVo);
            node.setVmCount(vmCount);

            BeanUtil.copyProperties(m, vo);
            vo.setType(type);
            vo.setNode(node);
            vo.setRegion(tbRegionVo);
            return vo;
        }).collect(Collectors.toList());

        return machineVoList;
    }

    @PutMapping("/node/{nodeId}")
    public Boolean updateNode(@PathVariable("nodeId") String nodeId,
                              @RequestBody TbNode tbNode){
        TbNode tbNode1 = new TbNode();
        tbNode1.setCreateTime(LocalDateTime.now());
        tbNode1.setUpdateTime(LocalDateTime.now());
        BeanUtil.copyProperties(tbNode,tbNode1);
        tbNode1.setId(nodeId);
        boolean flag = iTbNodeService.updateById(tbNode1);
        return flag;
    }

    @DeleteMapping("/node/{nodeId}")
    public Boolean deleteNode(@PathVariable("nodeId") String nodeId){
        boolean flag = iTbNodeService.removeById(nodeId);
        return flag;
    }


    @GetMapping("/node/nodeCollect")
    public List<NodeCountVo> nodeCount(){
        List<TbPartner> tbPartnerList = iTbPartnerService.lambdaQuery()
                .list();

        List<NodeCountVo> nodeCountVoList = tbPartnerList.stream().map(tbPartner -> {
            //获取合作商名称
            String name = tbPartner.getName();

            //根据id查询合作商点位数量
            Integer id = tbPartner.getId();
            Integer value = iTbNodeService.lambdaQuery()
                    .eq(id != null, TbNode::getOwnerId, id)
                    .count();
            NodeCountVo nodeCountVo = new NodeCountVo();
            nodeCountVo.setName(name);
            nodeCountVo.setValue(value);
            return nodeCountVo;
        }).collect(Collectors.toList());
        return nodeCountVoList;
    }

    @GetMapping("/node/count")
    public Integer getNodeCount(){
        Integer count = iTbNodeService.lambdaQuery()
                .count();
        return count;
    }
}
